package com.dmcbig.mediapicker;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dmcbig.mediapicker.adapter.MyITHCallback;
import com.dmcbig.mediapicker.adapter.ThumbnailAdapter;
import com.dmcbig.mediapicker.entity.Media;
import com.dmcbig.mediapicker.utils.FileUtils;
import com.dmcbig.mediapicker.view.PreviewFragment;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dmcBig on 2017/8/9.
 */

public class PreviewActivity extends AppCompatActivity implements View.OnClickListener,ViewPager.OnPageChangeListener{
    private static final String TAG = "PreviewActivity";

    private boolean fromPreviewButton = true; //来自“预览”按钮
    private int maxCount;           //最大可选数
    private int position;           //不是从预览按钮过来的item的index
    private long maxSize;           //最大可选大小  50M

    public static PreviewActivity previewActivity;

    RelativeLayout rlThumbnail; //缩略图布局
    RecyclerView rvThumbnail;  //缩略图

    private Media _media = null;//拖动刷新之前显示的对象

    Button done;                //发送
    LinearLayout check_layout;  //对勾+文字
    ImageView check_image;  //选中图片 对勾
    public ViewPager viewpager;
    TextView bar_title;     //  8/9
    public ArrayList<Media> preRawList,selects;  //preRawList--原始选中  selects--修改后
    ArrayList<Fragment> fragmentArrayList=new ArrayList<>(); //viewPager显示Fragment
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        previewActivity = this;
        setContentView(R.layout.preview_main);

        //最大可选择数
        maxCount = getIntent().getIntExtra(PickerConfig.MAX_SELECT_COUNT,PickerConfig.DEFAULT_SELECTED_MAX_COUNT);
        //不是从“预览”按钮过来的
        position = getIntent().getIntExtra(PickerConfig.ITEM_INDEX,0);
        maxSize = getIntent().getLongExtra(PickerConfig.MAX_SELECT_SIZE,PickerConfig.DEFAULT_SELECTED_MAX_SIZE);

        rlThumbnail = (RelativeLayout) findViewById(R.id.rl_thumbnail);
        rvThumbnail = (RecyclerView) findViewById(R.id.rv_thumbnail);

        findViewById(R.id.btn_back).setOnClickListener(this);
        check_image=(ImageView) findViewById(R.id.check_image);
        check_layout=(LinearLayout) findViewById(R.id.check_layout);
        check_layout.setOnClickListener(this);
        bar_title=(TextView) findViewById(R.id.bar_title);
        done=(Button) findViewById(R.id.done);
        done.setOnClickListener(this);
        viewpager=(ViewPager) findViewById(R.id.viewpager);



        //若是来自“预览”按钮，表示原始选中list   否则表示所有list
        preRawList=getIntent().getParcelableArrayListExtra(PickerConfig.PRE_RAW_LIST);
        fromPreviewButton = getIntent().getBooleanExtra(PickerConfig.FROM_PREVIEW_BUTTON,true);
        if (fromPreviewButton) {
            for (Media media : preRawList) {
                media.setChoosed(true);
            }
            selects=new ArrayList<>();
        } else {
            //已经选择的list
            selects = getIntent().getParcelableArrayListExtra(PickerConfig.DEFAULT_SELECTED_LIST);
        }

        setView(preRawList);

        showThumbnail();
    }

    void setView(ArrayList<Media> default_list){
        setDoneView();

        if (fromPreviewButton) {
            bar_title.setText(1 + "/" + preRawList.size());
        } else {
            bar_title.setText(position+1 + "/" + preRawList.size());
        }

        fragmentArrayList.clear();
        for(Media media:default_list){
            fragmentArrayList.add( PreviewFragment.newInstance(media,""));
        }
        AdapterFragment adapterFragment=new AdapterFragment(getSupportFragmentManager(),fragmentArrayList);
        viewpager.setAdapter(adapterFragment);
        if (!fromPreviewButton) {
            viewpager.setCurrentItem(position,false);
        }
        viewpager.addOnPageChangeListener(this);
    }

    //更新selects··
    void setDoneView(){
        if (fromPreviewButton) {
            selects.clear();
            for (Media media : preRawList) {
                if (media.isChoosed()) {
                    selects.add(media);
                }
            }
        }
        int num1 = selects.size();
        if (num1 == 0 ) {
            rlThumbnail.setVisibility(View.GONE);
            done.setText(getString(R.string.done));
            done.setEnabled(false);
        } else {
            done.setEnabled(true);
            rlThumbnail.setVisibility(View.VISIBLE);
            done.setText(getString(R.string.done)+"("+num1+"/"+maxCount+")");
        }
    }

    //list顺序改变后更新,直接preRawList已经改变了
    public void updatePreRawList() {
        if (fromPreviewButton) {
            setView(preRawList);
            //拖动前显示的图片在拖动后list中的index
            if (_media != null) {
                int index = isSelect(_media,preRawList);
                if (index > -1) {
                    viewpager.setCurrentItem(index,false);
                    ((ThumbnailAdapter) rvThumbnail.getAdapter()).updateBox(index);
                }
            }
            setDoneView();
        } else {
            if (_media != null) {
                int index = isSelect(_media,selects);
                if (index > -1) {
                    ((ThumbnailAdapter) rvThumbnail.getAdapter()).updateBox(index);
                }
            }
        }

    }

    //显示缩略图
    private void showThumbnail() {
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvThumbnail.setLayoutManager(llm);

        if (fromPreviewButton) {
            ThumbnailAdapter adapter = new ThumbnailAdapter(fromPreviewButton,rvThumbnail,this,preRawList);
            rvThumbnail.setAdapter(adapter);
            ItemTouchHelper itHelper = new ItemTouchHelper(new MyITHCallback(adapter,preRawList));
            itHelper.attachToRecyclerView(rvThumbnail);
        } else {
            ThumbnailAdapter adapter = new ThumbnailAdapter(fromPreviewButton,rvThumbnail,this,selects);
            rvThumbnail.setAdapter(adapter);
            ItemTouchHelper itHelper = new ItemTouchHelper(new MyITHCallback(adapter,selects));
            itHelper.attachToRecyclerView(rvThumbnail);
            int selectIndex = isSelect(preRawList.get(position),selects);
            if (selectIndex >= 0) {
                check_image.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.btn_selected));
            } else {
                check_image.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.btn_unselected));
            }
            adapter.updateBox(selectIndex);
        }

    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        if(id==R.id.btn_back){
            done(selects,PickerConfig.RESULT_UPDATE_CODE);
        }else if(id==R.id.done){
            done(selects,PickerConfig.RESULT_CODE);
        }else if(id==R.id.check_layout){
            Media media=preRawList.get(viewpager.getCurrentItem());
            if (fromPreviewButton) {
                if (media.isChoosed()) {
                    check_image.setImageDrawable( ContextCompat.getDrawable(this, R.drawable.btn_unselected));
                    media.setChoosed(false);
                } else {
                    check_image.setImageDrawable( ContextCompat.getDrawable(this, R.drawable.btn_selected));
                    media.setChoosed(true);
                }
                rvThumbnail.getAdapter().notifyDataSetChanged();
            } else {
                int selectIndex = isSelect(media,selects);
                if (selects.size()>=maxCount && selectIndex<0) {
                    Toast.makeText(this,getString(R.string.msg_amount_limit),Toast.LENGTH_SHORT).show();
                } else {
                    if (media.size > maxSize) {
                        Toast.makeText(this,getString(R.string.msg_size_limit)+(FileUtils.fileSize(maxSize)),Toast.LENGTH_LONG).show();
                    } else {
                        if (selectIndex >= 0) {
                            check_image.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.btn_unselected));
                            selects.remove(selectIndex);
                            ((ThumbnailAdapter) rvThumbnail.getAdapter()).updateBox(-1);
                        } else {
                            check_image.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.btn_selected));
                            selects.add(media);
                            ((ThumbnailAdapter) rvThumbnail.getAdapter()).updateBox(selects.size()-1);
                        }
                    }
                }

            }
            setDoneView();
        }
    }

    /**
     *
     * @param media
     * @return 大于等于0 就是表示以选择，返回的是在selectMedias中的下标
     */
    public int isSelect(Media media,ArrayList<Media> list){
        int is=-1;
        if(list.size()<=0){
            return is;
        }
        for(int i=0;i<list.size();i++){
            Media m=list.get(i);
            if(m.path.equals(media.path)){
                is=i;
                break;
            }
        }
        return is;
    }

    public void done(ArrayList<Media> list,int code){
        Intent intent=new Intent();
        intent.putParcelableArrayListExtra(PickerConfig.EXTRA_RESULT,list);
        setResult(code,intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        done(selects,PickerConfig.RESULT_UPDATE_CODE);
        super.onBackPressed();
    }

    public class AdapterFragment extends FragmentStatePagerAdapter {
        private List<Fragment> mFragments;

        public AdapterFragment(FragmentManager fm, List<Fragment> mFragments) {
            super(fm);
            this.mFragments = mFragments;
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        _media = preRawList.get(position);
        bar_title.setText((position + 1) + "/" + preRawList.size());

        if (fromPreviewButton) {
            ((ThumbnailAdapter) rvThumbnail.getAdapter()).updateBox(position);
            check_image.setImageDrawable(_media.isChoosed() ? ContextCompat.getDrawable(this, R.drawable.btn_selected) : ContextCompat.getDrawable(this, R.drawable.btn_unselected));
        } else {
            int selectIndex = isSelect(_media,selects);
            if (selectIndex >= 0) {
                check_image.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.btn_selected));
            } else {
                check_image.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.btn_unselected));
            }
            ((ThumbnailAdapter) rvThumbnail.getAdapter()).updateBox(selectIndex);
        }


//        check_image.setImageDrawable(isSelect(preRawList.get(position),selects)< 0 ? ContextCompat.getDrawable(this, R.drawable.btn_unselected) : ContextCompat.getDrawable(this, R.drawable.btn_selected));

    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
}
